package com.example.autopia.view.Fragments

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.autopia.databinding.FragmentNewsBinding
import com.example.autopia.model.Item.News
import com.example.autopia.model.Repositories.NewsRepository
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.view.Activities.AddNewsActivity
import com.example.autopia.view.Activities.ChannelsActivity
import com.example.autopia.view.Activities.CommentsActivity
import com.example.autopia.view.Activities.MyNewsActivity
import com.example.autopia.view.Adapters.NewsAdapter
import com.example.autopia.view.Listeners.ActionNewsListener
import com.example.autopia.view.Listeners.PostNewsListener
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase


class NewsFragment : Fragment() {

    private lateinit var binding: FragmentNewsBinding
    private val newsRepository = NewsRepository()
    private val userRepository = UsersRepository()
    private val firebaseAuth = Firebase.auth
    private val adapter = NewsAdapter()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        binding = FragmentNewsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.recyclerView.adapter = adapter
        getData()//Установка данных

        binding.swipeLayout.setOnRefreshListener {//Для обновления списка
            getData()
        }

        adapter.attachListenerAction(object : ActionNewsListener {
            //Переход на действия
            override fun onAddNewsClick() {
                startActivity(Intent(requireContext(), AddNewsActivity::class.java))
            }

            override fun onMyNewsClick() {
                startActivity(Intent(requireContext(), MyNewsActivity::class.java))
            }

            override fun onNewsChannelsClick() {
                startActivity(Intent(requireContext(), ChannelsActivity::class.java))
            }
        })

        binding.etSearch.addTextChangedListener(object : TextWatcher {
            //Поиск по всем новостям
            private val searchDelay = 600L
            private val handler = Handler()
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun afterTextChanged(s: Editable?) {
                binding.loading.visibility = View.VISIBLE
                binding.recyclerView.visibility = View.GONE
                handler.removeCallbacksAndMessages(null) // Сбрасываем предыдущую задержку
                handler.postDelayed({
                    performSearch()//Выполняем поиск
                }, searchDelay)
            }
        })

        adapter.attachListenerPost(object : PostNewsListener {
            override fun onAddCommentClick(news: News) {//Добавление коментария
                val intent = Intent(requireContext(), CommentsActivity::class.java)
                intent.putExtra("newsId", news.id)
                startActivity(intent)
            }
            override fun onAddLikeClick(news: News, isAdd: Boolean) {//Добавление/удаление лайка
                if (isAdd) {
                    newsRepository.addLike(newsId = news.id)
                    userRepository.addLikesNews(firebaseAuth.currentUser?.uid ?: "", news.id)
                } else {
                    newsRepository.removeLike(newsId = news.id)
                    userRepository.removeLikesNews(firebaseAuth.currentUser?.uid ?: "", news.id)
                }
            }
            override fun onMoreClick(news: News) {//Поделиться
                val intent = Intent(Intent.ACTION_SEND)
                intent.type = "text/plain"
                intent.putExtra(
                    Intent.EXTRA_TEXT,
                    "Обсуждение из 'Autopia'" + "\n \n" + news.title + "\n \n" + news.mainText + "\n \n" + news.name
                )
                startActivity(Intent.createChooser(intent, "Поделиться с помощью"))
            }
            override fun onDeleteClick(news: News) {//Удаление
                newsRepository.deleteNews(newsId = news.id)
                Toast.makeText(requireContext(), "Обсуждение удалено", Toast.LENGTH_SHORT).show()
                getData()
            }
            override fun onChannelCLick(userid: String) {//Переход на пользователя
                val intent = Intent(requireContext(), MyNewsActivity::class.java)
                intent.putExtra("id", userid)
                startActivity(intent)
            }
        })
    }

    private fun getData() {//Обычное получение данных
        val list = ArrayList<News>()
        val items = newsRepository.getAllItems()
        items.observe(viewLifecycleOwner) {
            val sortList = (it.sortedByDescending { news -> news.time }).take(10)//До 10 последних постов
            Log.d("Yatoro", sortList.size.toString())
            list.addAll(sortList)
            //Добавление вспомогательных элементов
            list.add(0, News("1", "1", "1", 1, null, "1", "1", 3, "1"))
            list.add(0, News("1", "", "1", 1, null, "1", "1", 0, ""))
            list.add(list.size, News("1", "", "1", 1, null, "1", "1", 4, ""))

            val user = userRepository.getUserById(firebaseAuth.currentUser?.uid ?: "")
            user.observe(viewLifecycleOwner) { curUser ->
                adapter.setData(list, curUser.likesNewsList!!)//Ставим чтобы отследить те посты, что понравились пользователю
                binding.loading.visibility = View.GONE
                binding.swipeLayout.isRefreshing = false
            }
            Log.d("Yatoro", it.size.toString() + " в observe")
        }
    }

    fun performSearch() {
        var list = ArrayList<News>()
        val items = newsRepository.getAllItems()
        items.observe(viewLifecycleOwner) {
            val sortList = (it.sortedByDescending { news -> news.time })
            list.addAll(sortList)
            list = list.filter { news ->
                news.name.contains(
                    binding.etSearch.text.toString().trim()
                ) || news.title.contains(binding.etSearch.text.toString().trim()) //Только удовлетворяющее поиску по названию и заголовку
            } as ArrayList<News>
            //Добавление вспомогательных элементов
            list.add(0, News("1", "1", "1", 1, null, "1", "1", 3, "1"))
            list.add(0, News("1", "", "1", 1, null, "1", "1", 0, ""))
            list.add(list.size, News("1", "", "1", 1, null, "1", "1", 4, ""))

            val user = userRepository.getUserById(firebaseAuth.currentUser?.uid ?: "")
            user.observe(requireActivity()) { curUser ->
                adapter.setData(list, curUser.likesNewsList ?: ArrayList())//Ставим чтобы отследить те посты, что понравились пользователю
                binding.loading.visibility = View.GONE
                binding.recyclerView.visibility = View.VISIBLE
            }
        }
    }
}